package com.dnxh.config;

import cn.hutool.core.util.StrUtil;
import com.dnxh.constant.CommonConstant;
import com.dnxh.entity.Account;
import com.dnxh.service.AccountService;
import com.dnxh.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * @Author 枳湫
 * @Time 2022/4/6 10:55
 * @Describe Basic_jar
 **/
@Slf4j
public class CustomRealm extends AuthorizingRealm {
	
	@Resource
	private AccountService accountService;
	
	@Override
	public boolean supports (AuthenticationToken token) {
		return token instanceof JwtToken;
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {
		log.info ("------------身份认证开始------------");
		String name = JwtUtil.decode (principalCollection.toString ()).get (CommonConstant.JWT_USER_NAME).toString ();
		Account role = accountService.selectRoleByUserName (name);
		if (role == null) {
			return null;
		} else {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo ();
			info.addRole (role.getIdentity ());
			return info;
		}
	}
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken authenticationToken) throws AuthenticationException {
		log.info ("------------添加角色权限等相关信息------------");
		String jwtToken = authenticationToken.getPrincipal ().toString ();
		if (StrUtil.isEmpty (jwtToken) || !JwtUtil.isVerify (jwtToken)){
			throw new AuthenticationException ("Token认证失败");
		}
		return new SimpleAuthenticationInfo (jwtToken, jwtToken, getName ());
	}
}
